package logic

import (
	"context"
	"github.com/pkg/errors"
	"yangming-college/app/usercenter/cmd/v1/rpc/internal/svc"
	"yangming-college/app/usercenter/cmd/v1/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCasRuleLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddCasRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCasRuleLogic {
	return &AddCasRuleLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddCasRuleLogic) AddCasRule(in *pb.AddCasRuleReq) (*pb.AddCasRuleResp, error) {
	for _, rule := range in.Rules {
		_, err := l.svcCtx.Enforcer.AddPolicy(rule.Sub, rule.Obj, rule.Act)
		if err != nil {
			return nil, errors.Wrapf(err, "添加casbinRule失败")
		}
	}

	if err := l.svcCtx.Enforcer.LoadPolicy(); err != nil {
		return nil, errors.Wrapf(err, "加载casbinRule失败")
	}

	return &pb.AddCasRuleResp{}, nil
}
